import React, { useEffect, useRef } from 'react';
import * as d3 from 'd3';

const ForceGraph = ({ data }) => {
  const svgRef = useRef();
  const width = 600;
  const height = 400;

  useEffect(() => {
    if (!data || data.length === 0) return;

    d3.select(svgRef.current).selectAll("*").remove();

    const svg = d3.select(svgRef.current)
      .attr("width", width)
      .attr("height", height);

    const simulation = d3.forceSimulation(data)
      .force("charge", d3.forceManyBody().strength(50))
      .force("center", d3.forceCenter(width / 2, height / 2))
      .force("collision", d3.forceCollide()
        .strength(0.7)
        .radius(d => d.radius + 2)
        .iterations(1)
      )
      .force("x", d3.forceX(width / 2).strength(0.05))
      .force("y", d3.forceY(height / 2).strength(0.05));

    const nodes = svg.append("g")
      .selectAll("circle")
      .data(data)
      .enter()
      .append("g");

    nodes.append("circle")
      .attr("r", d => d.radius)
      .attr("fill", "#69b3a2")
      .attr("stroke", "#333");

    nodes.append("text")
      .attr("dy", ".3em")
      .attr("text-anchor", "middle")
      .style("font-size", "12px")
      .style("fill", "#333")
      .text(d => d.label);

    simulation.on("tick", () => {
      nodes
        .attr("transform", d => `translate(${d.x},${d.y})`);
    });

    return () => {
      simulation.stop();
    };
  }, [data]);

  return <svg ref={svgRef}></svg>;
};

export default ForceGraph;